package com.yimi.yinhepda.views.dispatch_module;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import butterknife.Bind;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.DispatchBackReasonAdapter;
import com.yimi.yinhepda.adapter.DispatchBackScanAdapter;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.entity.bean.BackReasonEntity;
import com.yimi.yinhepda.entity.bean.DispatchBackScanChildEntity;
import com.yimi.yinhepda.entity.bean.DispatchBackScanEntity;
import com.yimi.yinhepda.entity.request.DispatchBackScanRquest;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.base.BaseInitActivity;
import java.util.ArrayList;
import java.util.List;

/**
 * 配送退单扫描界面
 *
 * @author 000432
 * @date 2018/3/7 0007
 */
public class DispatchBackScanActivity extends BaseInitActivity implements AdapterView.OnItemSelectedListener {

  /** 退单原因列表 */
  @Bind(R.id.dispatch_back_scan_spinner) Spinner mBackReasonList;
  /** 添加扫描按钮 */
  @Bind(R.id.back_scan_add) Button mAddBtn;
  /** 撤销扫描按钮 */
  @Bind(R.id.back_scan_delete) Button mDleBtn;
  /** 退单扫描列表 */
  @Bind(R.id.back_scan_listview) ListView mListView;
  @Bind(R.id.back_hasScan) TextView mHasScan;
  public static List<DispatchBackScanEntity> mScanList;
  private DispatchBackScanAdapter mScanAdapter;
  /** 备注对话框 */
  private Dialog remarkDialog;
  /** 备注信息 */
  private String remark = "";

  public DispatchBackScanActivity() {
    super(true);
  }

  @Override public String getPageName() {
    return getString(R.string.dispatchBackScan);
  }

  @Override public int getContentViewId() {
    return R.layout.activity_dispatch_back_scan;
  }

  @Override public void initView(Bundle savedInstanceState) {

  }

  @Override public void initEvent() {
    mBackReasonList.setOnItemSelectedListener(this);
    findViewById(R.id.back_scan_add).setOnClickListener(this);
    findViewById(R.id.back_scan_delete).setOnClickListener(this);
    findViewById(R.id.back_scan_back).setOnClickListener(this);
    findViewById(R.id.back_scan_ok).setOnClickListener(this);

    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        DispatchBackScanEntity entity = mScanList.get(position);
        Intent intent = new Intent(DispatchBackScanActivity.this, DispatchBackScanDetail.class);
        intent.putExtra("DispatchBackScanEntity", entity);
        startActivity(intent);
      }
    });
  }

  @Override public void initData() {
    ((TextView) findViewById(R.id.title)).setText(getString(R.string.dispatchBackScan));
    findViewById(R.id.num).setVisibility(View.GONE);

    mScanList = new ArrayList<>();

    List<BackReasonEntity> backReasonEntities = new ArrayList<>();
    backReasonEntities.add(new BackReasonEntity("请选择", "0"));
    backReasonEntities.add(new BackReasonEntity("货单不一（少装、漏装、串货）", "1"));
    backReasonEntities.add(new BackReasonEntity("货损货差", "2"));
    backReasonEntities.add(new BackReasonEntity("客户临时改约", "3"));
    backReasonEntities.add(new BackReasonEntity("送货不及时", "4"));
    backReasonEntities.add(new BackReasonEntity("客户拒收", "5"));
    backReasonEntities.add(new BackReasonEntity("其他（需备注）", "6"));

    DispatchBackReasonAdapter backReasonAdapter = new DispatchBackReasonAdapter(this, backReasonEntities);
    mBackReasonList.setAdapter(backReasonAdapter);

    mScanAdapter = new DispatchBackScanAdapter(this, mScanList);
    mListView.setAdapter(mScanAdapter);
  }

  @Override public void onClick(View v) {
    switch (v.getId()) {
      case R.id.back_scan_add:
        if (mBackReasonList.getSelectedItemPosition() == 0) {
          SoundVibratorManager.playSound(2);
          showToast("请先选择退单原因！");
          return;
        }
        //添加按钮
        toActivity(DispatchBackScanAddActivity.class);
        break;
      case R.id.back_scan_delete:
        //撤销按钮
        toActivity(DispatchBackScanDelActivity.class);
        break;
      case R.id.back_scan_back:
        activityBack();
        break;
      case R.id.back_scan_ok:
        if (mScanList != null && mScanList.size() <= 0) {
          SoundVibratorManager.playSound(2);
          showToast("无扫描运单不可提交！");
          return;
        }

        if (mBackReasonList.getSelectedItemPosition() == 0) {
          SoundVibratorManager.playSound(2);
          showToast("请先选择退单原因！");
          return;
        }

        MyDialog dialog = new MyDialog(this);
        dialog.setIcon(R.drawable.alert);
        dialog.setMessage("提交后数据不可修改，是否继续？");
        dialog.setPositiveClickListener( Constants.confirmMsg, new DialogInterface.OnClickListener() {
          @Override public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            //提交数据
            submitData();
          }
        });
        dialog.setNegativeClickListener(R.drawable.btn_cancel_selector, Constants.cancelMsg, null);
        dialog.show();
        break;
      default:
        break;
    }
  }

  /**
   * 提交配送退单数据
   */
  private void submitData() {
    List<Long> lists = new ArrayList<>();
    for (DispatchBackScanEntity entity : mScanList) {
      lists.add(Long.parseLong(entity.getWayBillNo()));
    }

    DispatchBackScanRquest dispatchBackScanRquest = new DispatchBackScanRquest();
    dispatchBackScanRquest.setWaybillNo(lists);
    dispatchBackScanRquest.setBackReason(mBackReasonList.getSelectedItemPosition());
    dispatchBackScanRquest.setUserCode(sharedPreferUtil.getWorkNum());
    dispatchBackScanRquest.setDeptCode(sharedPreferUtil.getDeptCode());
    dispatchBackScanRquest.setDeptName(sharedPreferUtil.getValue(Common.DEPT_NAME));
    dispatchBackScanRquest.setCompCode(sharedPreferUtil.getCompanyCode());
    dispatchBackScanRquest.setRemark(remark);

    setScannerEnabled(false);
    showPgDlg("正在提交扫描数据...");

    new NetRequest().setUrl(Constants.DISPATCH_BACK_SCAN_URL)
        .setRequestObject(dispatchBackScanRquest)
        .setMethod(NetRequest.Method.POST_STRING)
        .setResponsClazz(Object.class)
        .execute(new UICallBack() {
          @Override public void onError(String msg) {
            setScannerEnabled(true);
            dismissPgDlg();
            SoundVibratorManager.playSound(2);
            //对话框提示用户非派送状态的运单
            LinearLayout layout =
                (LinearLayout) LayoutInflater.from(DispatchBackScanActivity.this).inflate(R.layout.alert_dialog_back_scan_error, null);
            TextView tvError = (TextView) layout.findViewById(R.id.tv_back_scan_error);
            Button btnOK = (Button) layout.findViewById(R.id.back_scan_error_ok);
            tvError.setMovementMethod(ScrollingMovementMethod.getInstance());
            tvError.setText(msg);
            final Dialog dialog = new Dialog(DispatchBackScanActivity.this, R.style.AsyncTaskDialog);
            dialog.addContentView(layout,
                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            dialog.getWindow().getDecorView().setPadding(10, 0, 10, 0);
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();

            btnOK.setOnClickListener(new View.OnClickListener() {
              @Override public void onClick(View v) {
                dialog.dismiss();
              }
            });
          }

          @Override public void onSuccess(Object obj) {
            mBackReasonList.setSelection(0);
            mScanList.clear();
            remark = "";
            flashListData();
            showToast("提交数据成功！");
            setScannerEnabled(true);
            dismissPgDlg();
            SoundVibratorManager.playSound(1);
          }
        });
  }

  @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
      activityBack();
    }
    return false;
  }

  private void activityBack() {
    if (mScanList != null && mScanList.size() > 0) {
      MyDialog dialog = new MyDialog(this);
      dialog.setIcon(R.drawable.alert);
      dialog.setMessage("退出后扫描数据将被放弃，是否继续？");
      dialog.setPositiveClickListener(Constants.confirmMsg, new DialogInterface.OnClickListener() {
        @Override public void onClick(DialogInterface dialog, int which) {
          dialog.dismiss();
          finish();
        }
      });
      dialog.setNegativeClickListener(R.drawable.btn_cancel_selector, Constants.cancelMsg, null);
      dialog.show();
    } else {
      finish();
    }
  }

  @Override protected void onResume() {
    super.onResume();
    flashListData();
  }

  @Override protected void handleBarCode(String result) {
    if (result == null) {
      SoundVibratorManager.playSound(2);
      showToast("运单号扫描失败");
    } else {
      doScan(result);
    }
  }

  /**
   * 处理扫描
   */
  protected void doScan(String result) {
    if (mBackReasonList.getSelectedItemPosition() == 0) {
      SoundVibratorManager.playSound(2);
      showToast("请先选择退单原因！");
      return;
    }

    if (!StringUtils.isWaybillNo(result) && !StringUtils.isPackgeNo(result)) {
      SoundVibratorManager.playSound(2);
      showToast("单号或包号不规范!");
      return;
    }
    //遍历子单号是否在列表中
    boolean inChildList = false;
    for (DispatchBackScanEntity item : mScanList) {
      for (DispatchBackScanChildEntity childItem : item.getChildEntityList()) {
        if (result.equals(childItem.getChildWaybillNo())) {
          inChildList = true;
        }
      }
    }
    if (inChildList) {
      SoundVibratorManager.playSound(2);
      showToast("运单号已扫描！");
      return;
    }
    //遍历主单号是否在列表中
    DispatchBackScanEntity scanEntity = null;
    boolean inList = false;
    String waybillNo = result.substring(0, 12);
    for (DispatchBackScanEntity item : mScanList) {
      if (waybillNo.equals(item.getWayBillNo())) {
        scanEntity = item;
        inList = true;
      }
    }
    //不存在列表中，将扫描的运单加入到列表中
    if (!inList) {
      scanEntity = new DispatchBackScanEntity();
      scanEntity.setWayBillNo(waybillNo);
      scanEntity.setScanTime(DateHelper.getDateFormateOffline());
      scanEntity.setChildEntityList(new ArrayList<DispatchBackScanChildEntity>());
      mScanList.add(scanEntity);
    }
    DispatchBackScanChildEntity childEntity = new DispatchBackScanChildEntity();
    childEntity.setWaybillNo(waybillNo);
    childEntity.setChildWaybillNo(result);
    scanEntity.getChildEntityList().add(childEntity);
    scanEntity.setScanNum(scanEntity.getChildEntityList().size());

    //刷新数据
    flashListData();

    SoundVibratorManager.playSound(1);
  }

  /**
   * 刷新数据
   */
  private void flashListData() {
    mScanAdapter.setmList(mScanList);
    mScanAdapter.notifyDataSetChanged();
    mListView.setSelection(mScanAdapter.getCount() - 1);

    //设置已扫票/件
    int count = 0;
    for (DispatchBackScanEntity item : mScanList) {
      count += item.getChildEntityList().size();
    }
    mHasScan.setText(mScanList.size() + "/" + count);
  }

  @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    switch (parent.getId()) {
      case R.id.dispatch_back_scan_spinner:
        //选择其他时，显示备注框
        if (position == 6) {
          LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.alert_dialog_scan_back_remark, null);
          final EditText reamrkEt = (EditText) layout.findViewById(R.id.scan_back_remark);
          Button okBtn = (Button) layout.findViewById(R.id.scan_back_reamrk_ok);
          if (remark != null && !remark.equals("")) {
            reamrkEt.setText(remark);
          }
          if (remarkDialog == null) {
            remarkDialog = new Dialog(this, R.style.AsyncTaskDialog);
          }
          remarkDialog.addContentView(layout,
              new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
          remarkDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
          remarkDialog.getWindow().getDecorView().setPadding(10, 0, 10, 0);
          remarkDialog.setCanceledOnTouchOutside(false);
          remarkDialog.show();

          okBtn.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
              remark = reamrkEt.getText().toString().trim();
              remarkDialog.dismiss();
            }
          });
        }
        break;
      default:
        break;
    }
  }

  @Override public void onNothingSelected(AdapterView<?> parent) {
  }
}
